package com.android.bookgarden.tabfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.bookgarden.MainActivity;
import com.android.bookgarden.R;
import com.android.bookgarden.adapter.HomeDataAdapter;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseFragment;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.HomeAdvBean;
import com.android.bookgarden.bean.HomeDataBean;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.recycleview.BaseViewHolder;
import com.android.bookgarden.recycleview.EndLessOnScrollListener;
import com.android.bookgarden.ui.ClassroomDetailsActivity;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.lzy.okgo.model.HttpHeaders;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class HomeTabFragment extends BaseFragment implements RealtConstract.View {
    public static String TABLAYOUT_FRAGMENT = "tab_fragment";
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    Unbinder unbinder;

    private HomeDataAdapter adapter;
    private List<HomeDataBean> list;
    int type = -1;
    private RealtConstract.Presenter presenter;

    private int pageIndex = 1;
    private int pageSize = 4;
    private String mer_id;
    private boolean flag = false;


    public static HomeTabFragment newInstance(int type, int id) {
        HomeTabFragment fragment = new HomeTabFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(TABLAYOUT_FRAGMENT, type);
        bundle.putSerializable("mer_id", "" + id);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = (int) getArguments().getSerializable(TABLAYOUT_FRAGMENT);
            mer_id = (String) getArguments().getSerializable("mer_id");
        }

    }


    @Override
    protected int getLayoutId() {
        return R.layout.change_fragment;
    }

    @Override
    protected void initView() {
        presenter = new BasePersenter(this, getActivity());
        list = new ArrayList<>();
//        list.add(new HomeDataBean(true,"",11,""));
//        list.add(new HomeDataBean(true,"",11,""));
//        list.add(new HomeDataBean(true,"",11,""));
//        list.add(new HomeDataBean(true,"",11,""));
//        list.add(new HomeDataBean(true,"",11,""));
//        list.add(new HomeDataBean(true,"",11,""));
//        list.add(new HomeDataBean(true,"",11,""));
        pageIndex = 1;
        pageSize = 4;
        List<HomeAdvBean> advList = null;
//        HomeAdvBean bean = new HomeAdvBean();
//        bean.setUrl("http://photo.16pic.com/00/61/35/16pic_6135989_b.jpg");
//        advList.add(bean);
//        HomeAdvBean bean1 = new HomeAdvBean();
//        bean1.setUrl("http://img.zcool.cn/community/017ca7554570b20000019ae90be4b1.jpg@2o.jpg");
//        advList.add(bean1);
        if (type == 0) {
            advList = MainActivity.mainActivity.getAdvData();
        }

        adapter = new HomeDataAdapter(list, getActivity());
//        if (type==0){
//            final Map map = null;
//            presenter.loadData(map, "",Apis.GET_HOME_ADV+"1",1001);
//            adapter.setAdvClick(new AdvClickLister() {
//                @Override
//                public void onClick(String id) {
//                    presenter.loadData(map, "",Apis.CLICK_ADV+id,1);
//                }
//            });
//        }else{
//            getDataList();
//        }

        getDataList();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(manager);
        recycler.setHasFixedSize(true);

//        LinearLayoutManager linearLayoutManager=new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
//        recycler.setLayoutManager(linearLayoutManager);

        adapter.setOnItemClickLitener(new HomeDataAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, BaseViewHolder viewHolder) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean",list.get(position));
//                Intent intent = new Intent(getActivity(),ClassroomDetailsActivity.class)
                startActivity(ClassroomDetailsActivity.class,bundle);
            }
        });

        recycler.setAdapter(adapter);
        if (type == 0) {
            if (null != advList && advList.size() > 0) {
                adapter.addHeaderView(R.layout.home_layout_header, advList);
            }

        }
        adapter.addFooterView(R.layout.layout_footer);
//        adapter.addHeaderView(R.layout.home_layout_header,advList);

        recycler.addOnScrollListener(new EndLessOnScrollListener(manager) {
            @Override
            public void onLoadMore() {
                if (flag){
                pageIndex ++;
                if (list.size() != 0)
                    adapter.setFooterVisible(View.VISIBLE);
                getDataList();
                }
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshLayout.setRefreshing(true);
                pageIndex= 1;
                list.clear();
                adapter.notifyDataSetChanged();
                getDataList();
            }
        });

    }

    private void getDataList() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("token", MainActivity.mainActivity.token);
        presenter.loadDataHeader(null, "", Apis.GET_MERCHAT + pageIndex + "/" + pageSize + "/" + mer_id, 1002, headers, HttpType.GET);
    }

    @Override
    public void returnData(String data, int urlCode) {
        LogUtil.e("返回数据", data + "");


        handler.obtainMessage(urlCode, data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        if (urlCode==1002){
            refreshLayout.setRefreshing(false);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            switch (msg.what) {
                case 1001:
                    try {
                        getHomeAdv(data);
                        getDataList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 1002:
                    refreshLayout.setRefreshing(false);
                    if (TextUtils.isEmpty(data)){
                        adapter.setFooterVisible(View.GONE);
                        flag = false;
                        return;
                    }
                    DataBean bean = getDataBean(data);
                    if (null == bean) {
                        showToast("获取列表失败");
                        return;
                    }
                    if (bean.getCode() == 200) {
                        List<HomeDataBean> listD = JsonUitl.stringToList(bean.getData(), HomeDataBean.class);
                        if (null == listD || listD.size() <= 0) {
                            adapter.setFooterVisible(View.GONE);
                            flag = false;
                            return;
                        }
                        list.addAll(listD);
                        adapter.notifyDataSetChanged();
                        if (listD.size()<pageSize){
                            flag = false;
                            adapter.setFooterVisible(View.GONE);
                        }else{
                            flag = true;
                        }

                    } else {
                        showToast(bean.getMessage() + "");
                    }


                    break;
            }
        }
    };

    private void getHomeAdv(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        int code = object.getInt("code");
        if (code == 200) {
            List<HomeAdvBean> list = JsonUitl.stringToList(object.getString("data"), HomeAdvBean.class);
            if (type == 0) {
                adapter.addHeaderView(R.layout.home_layout_header, list);
            }
        }
    }

    private DataBean getDataBean(String json) {
        DataBean bean = new DataBean();
        try {
            JSONObject object = new JSONObject(json);
            bean.setCode(object.getInt("code"));
            bean.setData(object.getString("data"));
            bean.setMessage(object.getString("message"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return bean;
    }



    public interface AdvClickLister {
        void onClick(String id);
    }
}
